<script lang="ts" setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import sjyglService from '@/api/sjygl'
import dataEditorDialog from './dialogs/data-editor-dialog.vue'
import { SjyQueryResult, SjyTestInputDTO, SjyfzQueryResult } from '@/api/sjygl-dto'
import basePagination from '@/components/base-pagination/index.vue'
import sjyzj from './components/sjyzj.vue'
import LayoutContainer from '@/components/layout-container/index.vue'
// 入参
interface tableFace extends SjyQueryResult {
  checked: boolean
}
/* 初始化 */
const sjyfzmc = ref<string>('')
const initData = (data: SjyfzQueryResult) => {
  form.value.filter.sjyfzbh = data.sjyfzbh
  sjyfzmc.value = data.sjyfzmc
  handleCurrentChange(1)
}
onMounted(() => {
  const intervalId = setInterval(onetesting, 5 * 60 * 1000) // 每五分钟调用一次
  // 清理定时器
  onUnmounted(() => {
    clearInterval(intervalId)
  })
})
/*
 * 获取节点下数据源
 */
// 数据源查询条件
const form = ref({
  pageSize: 10,
  pageNum: 1,
  orderBy: '',
  filter: {
    sjymc: '', // 数据源名称
    sjylxdm: '', // 数据源类型代码
    sjyfzbh: '', // 数据源分组编号
    gjz: '',
  },
})
//分页总条数
const total = ref(0)
// 数据源列表
const tableData = ref<tableFace[]>([])
/*
获取table表单数据
 */
const getData = () => {
  const params = form.value
  sjyglService
    .querySjy(params)
    .then((res) => {
      //
      tableData.value = res.data.list.map((cur: SjyQueryResult): tableFace => {
        return {
          ...cur,
          checked: false,
        }
      })
      total.value = res.data.total
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}
/*
 * 添加数据源
 */
const dataEditorRef = ref()
const addData = () => {
  dataEditorRef.value.openDialog({
    sjyfzbh: form.value.filter.sjyfzbh,
    sjyfzmc: sjyfzmc.value,
  })
}

/*
 * 删除数据源
 */
const deleteData = (rows: SjyQueryResult[]) => {
  if (rows.length) {
    ElMessageBox.confirm('是否确定删除当前选择的数据?', '删除数据源', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        let params = {
          sjybh: rows.map((el) => {
            return el.sjybh
          }),
        }
        sjyglService
          .deleteSjy(params)
          .then(() => {
            ElMessage({
              type: 'success',
              message: '删除数据源成功',
            })
            // 分页查询列表数据
            handleCurrentChange(1)
          })
          .catch((err) => {
            !err.isError && ElMessage({ type: 'warning', message: err.message })
          })
      })
      .catch(() => {
        //
      })
  } else {
    ElMessage({ type: 'warning', message: '请选择需要删除的数据源' })
  }
}

/*
一键测试按钮
 */
const onetesting = () => {
  //判断是否选择了列表数据，如果没有则提示用户。
  if (!multipleSelection.value.length) {
    if (tableData.value.length) {
      test(tableData.value)
    } else {
      return ElMessage({
        type: 'warning',
        message: '当前页面无数据测试',
      })
    }
  } else {
    // 未勾选测试全部
    test(multipleSelection.value)
  }
}

/*
测试数据源接口
*/
const test = (rows: SjyQueryResult[]) => {
  const params = {
    //获取当前选择的列表数据中的数据源编号
    sjybhsz: rows.map((x) => {
      return x.sjybh
    }),
  } as SjyTestInputDTO
  //调用测试借口
  sjyglService
    .testSjy(params)
    .then((res) => {
      // let arr = res.data.sjyztsz.map((x: any) => {
      //   return `${x.sjymc}：连接${x.zhycljzt === 'Y' ? '成功' : '失败'}`
      // })
      ElMessage({
        type: 'success',
        // message: `${res.data.sjyztsz.length > 1 ? '一键测试执行完成' : arr} `,
        message: `测试完成`,
      })
      getData()
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}
/*
table多选框选中值
*/
// 表格选中
const multipleSelection: any = computed(() => {
  return tableData.value.filter((cur: any) => {
    return cur.checked
  })
})

/*
 * table修改事件
 */
const handleEdit = (row: SjyQueryResult) => {
  dataEditorRef.value.openDialog(row)
}

/*
 * 查看详情
 */
const lookDetail = (row: SjyQueryResult) => {
  dataEditorRef.value.openDialog(row, true)
}

/*
查询
 */
const handleCurrentChange = (val: number) => {
  form.value.pageNum = val
  getData()
}
/* 
新增分组
*/
const swxTreeRef = ref()
const addTree = () => {
  swxTreeRef.value.addTree()
}
/* 渲染url */
const getImgUrl = (zhycljzt: string) => {
  if (zhycljzt === 'Y') {
    // 测试成功显示图片
    return new URL(`/src/assets/images/xtgl/success.png`, import.meta.url).href
  } else {
    // 测试失败显示图片
    return new URL(`/src/assets/images/xtgl/error.png`, import.meta.url).href
  }
}
// 回显图片
const reloadImg = (dm: string) => {
  if (!dm) {
    return
  }
  try {
    return new URL(`/src/assets/images/default/${dm}.png`, import.meta.url).href
  } catch (error) {
    console.log(error, 'error')
  }
}
</script>
<template>
  <div class="container">
    <layout-container leftTitle="分组">
      <template #left-btn>
        <button class="btn_operation" @click="addTree">
          <i class="icon iconfont icon-tianjia"></i>
          新增分组
        </button>
      </template>
      <template #left> <sjyzj ref="swxTreeRef" @initData="initData" /> </template>
      <template #form>
        <div class="top-query">
          <el-form :inline="true" :model="form.filter" @submit.prevent class="el-form-query">
            <el-form-item label=" " label-width="0" class="form-item">
              <el-input
                v-model="form.filter.gjz"
                clearable
                maxlength="30"
                placeholder="请输入查询关键字"
                :suffix-icon="'Search'"
                class="input-search"
              />
            </el-form-item>
            <el-form-item class="form-item-btn">
              <el-button type="primary" @click="handleCurrentChange(1)">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #table>
        <div class="content">
          <div class="btn-div">
            <button class="btn-operation" @click="onetesting()" :disabled="!form.filter.sjyfzbh">
              一键测试
            </button>
            <button class="btn-operation" @click="addData" :disabled="!form.filter.sjyfzbh">
              新增
            </button>
            <button
              class="btn-operation"
              @click="deleteData(multipleSelection)"
              :disabled="multipleSelection.length < 1"
            >
              删除
            </button>
          </div>
          <div class="ele-table sjy-content">
            <div
              v-for="item in tableData"
              :key="item.sjybh"
              class="sjy-item"
              @dblclick="lookDetail(item)"
            >
              <el-checkbox v-model="item.checked" class="check-box"></el-checkbox>
              <img v-if="item.zhycljzt" class="sjy-test-zt" :src="getImgUrl(item.zhycljzt)" />
              <img class="sjy-item-img" :src="reloadImg(item.tbwjdz)" />
              <div class="sjy-item-content">
                <span class="sjy-item-title" :title="item.sjymc">{{ item.sjymc }}</span>
                <div class="flex">
                  <el-tag type="info">{{ item.sjylxmc }}</el-tag>
                </div>
                <p class="sjy-item-time" :title="item.cjsj">
                  {{ `创建时间：${item.cjsj}` }}
                </p>
                <div class="sjy-item-btns">
                  <!-- <span
                    class="icon iconfont icon-bianji icon-primary"
                    title="编辑"
                    @click.stop="handleEdit(item)"
                  ></span>
                  <span
                    class="iconfont icon-bianji icon-danger"
                    title="删除"
                    @click.stop="deleteData([item])"
                  ></span>
                  <span
                    class="iconfont icon-bianji icon-primary"
                    title="测试"
                    @click.stop="deleteData([item])"
                  ></span> -->

                  <button class="btn_operation" @click.stop="handleEdit(item)" title="编辑">
                    <span class="icon iconfont icon-bianji"></span>
                  </button>
                  <button class="btn_operation" @click.stop="deleteData([item])" title="删除">
                    <span class="icon iconfont icon-shanchu icon-danger"></span>
                  </button>
                  <button class="btn_operation" @click.stop="test([item])" title="测试">
                    <span class="icon iconfont icon-ceshi"></span>
                  </button>
                </div>
              </div>
            </div>
          </div>
          <div class="ele-page">
            <base-pagination
              v-model="form"
              :page-sizes="[10, 20, 50, 100]"
              :total="total"
              @change="getData"
            />
          </div>
        </div>
      </template>
    </layout-container>
    <!-- 打开新增弹窗 -->
    <data-editor-dialog ref="dataEditorRef" @handleCurrentChange="handleCurrentChange" />
  </div>
</template>
<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  .top-query {
    border: 1px solid var(--border-color);
    min-height: 51px;
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    // padding: 0px 10px 0px 15px;
    .el-form-query {
      width: 100%;
      display: flex;
      align-items: center;
      .form-item {
        width: 25%;
        float: left;
        margin-bottom: 0px;
        margin-right: 12px;
      }
      .form-item-btn {
        float: left;
        margin-bottom: 0px;
        margin-right: 0px;
      }
    }
  }
  .content {
    flex: 1;
    border: 1px solid var(--border-color);
    display: flex;
    flex-direction: column;
    height: 100%;

    .btn-div {
      height: 40px;
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      padding: 0px 10px;
    }

    .ele-table {
      flex: 1;
      padding-left: 10px;
      overflow: auto;
    }

    .ele-page {
      display: flex;
      justify-content: flex-end;
      padding: 0px 10px 10px 10px;
    }
  }
  .sjy-content {
    display: flex;
    flex-wrap: wrap;
    align-content: flex-start;
    position: relative;

    .sjy-item {
      height: 120px;
      display: flex;
      margin-right: 10px;
      margin-bottom: 10px;
      border-radius: 3px;
      padding: 15px 0 0 12px;
      cursor: pointer;
      position: relative;
      border: 1px solid var(--border-color);
    }
    @media screen and (max-width: 1920px) {
      /* 在屏幕宽度小于或等于1920px时应用的样式 */
      .sjy-item {
        width: calc(100% / 4 - 10px);
      }
    }
    @media screen and (max-width: 1440px) {
      /* 在屏幕宽度小于或等于1440px时应用的样式 */
      .sjy-item {
        width: calc(100% / 3 - 10px);
      }
    }
    .sjy-item-img {
      width: 64px;
      height: 64px;
      margin-left: 15px;
      border-radius: 4px;
    }
    .sjy-test-zt {
      position: absolute;
      right: -1px;
      top: -1px;
    }
    .sjy-item-content {
      flex: 1;
      margin-left: 10px;
      font-size: 14px;
      color: var(--color-deep);
      font-family: MicrosoftYaHei;
      display: flex;
      flex-direction: column;
      overflow: hidden;
    }
    .sjy-item-title {
      display: inline-block;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      width: 100%;
    }
    .flex {
      margin: 3px 0;
    }
    .sjy-item-time {
      color: var(--color-shallow);
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      width: 100%;
    }
    .sjy-item-btns {
      margin-top: 7px;
      .iconfont {
        margin-right: 0;
      }
      .pictur-box {
        cursor: pointer;
      }
    }
  }
  .check-box {
    position: absolute;
    top: 0px;
    left: 5px;
    z-index: 100;
  }
}
</style>
